<template>
	<view class="content">
		<o-navbarx :back="true" :isback="false" color="#000000" title="订单详情" background="#ffffff"></o-navbarx>
		<view class="order_top poAb top-0 width-100 left-0"></view>
		<view class="martop_view pad-lr-30 poRe">
			<view class="fontSize-32 mar-top-30" v-if="info?.order.order_status==1">订单待支付</view>
			<view class="fontSize-28 mar-top-8 display align-items" v-if="info?.order.order_status==1&&order_type==1">请在<tm-countdown
					ref="cu" :autoStart="true" color="#E23737" :time="info?.order.count_down"
					format="MM分SS秒"></tm-countdown>内付款，超时订单将关闭</view>
			<view class="fontSize-32 mar-top-30" v-if="info?.order.order_status==10">订单带备货</view>
			<view class="fontSize-32 mar-top-30" v-if="info?.order.order_status==15">订单待发货</view>
			<view class="fontSize-32 mar-top-30" v-if="info?.order.order_status==20">订单待收货</view>
			<view class="fontSize-32 mar-top-30" v-if="info?.order.order_status==30">订单已完成</view>
			<view class="fontSize-32 mar-top-30" v-if="info?.order.order_status==40">订单已售后</view>
			<view class="fontSize-32 mar-top-30" v-if="info?.order.order_status==90">订单已取消</view>
			<view class="fontSize-32 mar-top-30" v-if="type==2">
				{{info?.after.status==1?'待处理':info?.after.status==20?'处理中':info?.after.status==30?'已完成':info?.after?.status==50?'拒绝':'已取消'}}
			</view>
			<view class="fontSize-32 mar-top-30" v-if="type==2">
				{{info?.after?.return_type==1?'退款':info?.after?.return_type==2?'换货':info?.after?.return_type==3?'退货退款':'仅退款'}}
			</view>
			<view class="fontSize-32 mar-top-30"
				v-if="type==2&&(info?.after?.return_type==2||info?.after?.return_type==3)">
				{{info?.after?.logistics_flow==1?'待用户寄出':info?.after?.logistics_flow==2?'用户已寄出':info?.after.logistics_flow==3?'待商家寄出':info?.after.logistics_flow==4?'商家已寄出':''}}
			</view>
			<view class="radius-16 bgfff pad-lr-20 pad-tb-30 mar-top-20 poRe" v-if="type!=2">
				<view class=" display-sb align-items">
					<view class="fontSize-30">
						<view class="">{{info?.order.name}} {{info?.order.mobile}}</view>
						<view class="display align-items mar-top-20">
							<text
								class="fontSize-28">{{info?.order.province}}{{info?.order.city}}{{info?.order.area}}{{info?.order.address}}</text>
						</view>
					</view>
				</view>
			</view>

			<view class="mar-top-20 pad-lr-20 pad-tb-20 bgfff radius-16">
				<view class="bgfff display align-items" v-for="(item,index) in (type==2?info?.after_goods:info?.goods)"
					:key="item.id" @click="gogoodsdetails(item.goods_id)">
					<image :src="type==2?item.image:item.image_text" class="proudct-item-icon-10 radius-16" mode="">
					</image>
					<view class="ml20 right_width">
						<view class="text-clamp-1 fontSize-28">{{item.name}}</view>
						<view class="display-sb align-items mar-top-20 fontSize-26">
							<text>{{item.sku_name}}</text><text>x{{item.num}}</text>
						</view>
						<view class="display-sb align-items mar-top-22">
							<view class="fontSize-28 col-E23737"><text class="fontSize-20">￥</text>{{item.price}}</view>

							<view class="pad-lr-32 pad-tb-12 fontSize-26 radius-30 col-f bg2DB295 ml20"
								v-if="item.is_evaluate==0&&info?.order_status==40&&item.after_status!=20&&item.after_status!=70"
								@click.stop="gowriteevaluate(item.id,item.order_id)">评价</view>
							<view class="pad-lr-32 pad-tb-12 fontSize-26 radius-30 col-f bg2DB295 ml20"
								v-if="(item.valid_num>0&&(info?.order.order_status==20||info?.order.order_status==30)&&info?.goods.length>1&&info?.order.is_refund==1)"
								@click.stop="goservice(item)">售后
							</view>
						</view>
					</view>
				</view>
				<view class="pad-tb-30 display-sb align-items border_bottom_F1 fontSize-26">
					<text>商品金额</text><text>￥{{info?.order.goods_money}}</text>
				</view>
				<view class="pad-tb-30 display-sb align-items border_bottom_F1 fontSize-26">
					<text>运费</text><text>￥{{info?.order.pay_freight_money}}</text>
				</view>
				<view class="pad-tb-30 display-sb align-items border_bottom_F1 fontSize-26">
					<text>应付款</text><text>￥{{info?.order.pay_price}}</text>
				</view>
			</view>
			<view class="mar-top-20 pad-lr-20 pad-tb-20 radius-16 bgfff">
				<view class="fontSize-28">订单信息</view>
				<view class="pad-tb-20 display-sb align-items border_bottom_F1 fontSize-26">
					<text>订单编号:</text><text>{{info?.order.order_no}}</text>
				</view>
				<view class="pad-tb-20 display-sb align-items fontSize-26"
					v-if="info?.order.order_status!=90&&info?.order.order_status!=1">
					<text>付款金额:</text><text>￥{{info?.order.pay_price}}</text>
				</view>
				<view class="pad-tb-20 display-sb align-items fontSize-26" v-if="type!=2">
					<text>下单时间:</text><text>{{info?.order.create_time}}</text>
				</view>
				<view class="pad-tb-20 display-sb align-items fontSize-26" v-if="type!=2&&info?.order.balance>0">
					<text>余额支付:</text><text>￥{{info?.order.balance}}</text>
				</view>

				<view class="pad-tb-20 display-sb align-items fontSize-26"
					v-if="(info?.order.order_status>1&&info?.pay_time)">
					<text>支付时间:</text><text>{{info?.order.pay_time}}</text>
				</view>
				<view class="pad-tb-20 display-sb align-items fontSize-26"
					v-if="(info?.order.order_status>15&&info?.order.order_status!=90)">
					<text>发货时间:</text><text>{{info?.order.deliver_time}}</text>
				</view>
				<view class="pad-tb-20 display-sb align-items fontSize-26"
					v-if="(info?.order.order_status>20&&info?.order.order_status!=90)">
					<text>收货时间:</text><text>{{info?.order.receive_time}}</text>
				</view>
				<!-- <view class="pad-tb-20 display-sb align-items fontSize-26 col-6" v-if="info?.order_status>20&&info?.order_status!=90">
			<text>发货单号:{{info?.express_code}}</text><text></text><text class="col-3 ml20" @click="copy(info?.express_code)">复制</text>
		</view> -->
				<view class="pad-tb-20 display-sb align-items fontSize-26" v-if="type==2">
					<text>提交售后审核时间:</text><text>{{info?.after.create_time}}</text>
				</view>
				<view class="pad-tb-20 display-sb align-items fontSize-26" v-if="type==2&&info?.after.status>1">
					<text>审核时间:</text><text>{{info?.after.handle_time}}</text>
				</view>
				<view class="pad-tb-20 display-sb align-items fontSize-26"
					v-if="type==2&&info?.after?.return_type!=2&&info?.after.status==30">
					<text>退款时间:</text><text>{{info?.after.refund_time}}</text>
				</view>
				<view class="pad-tb-20 display-sb align-items fontSize-26"
					v-if="type==2&&info?.after?.return_type!=2&&info?.after.status==30">
					<text>退款金额:</text><text>{{info?.after.actual_money}}</text>
				</view>
				<view class="pad-tb-20 display-sb align-items fontSize-26" v-if="type==2&&(info?.after.status==50)">
					<text>审核不通过原因:</text><text>{{info?.after.reject_reason}}</text>
				</view>
				<view class="pad-tb-20 display-sb align-items fontSize-26" v-if="type==2">
					<text>商家收件姓名:</text><text>{{info?.shop_mail.mail_name}}</text>
				</view>
				<view class="pad-tb-20 display-sb align-items fontSize-26" v-if="type==2">
					<text>商家收件电话:</text><text>{{info?.shop_mail.mail_mobile}}</text>
				</view>
				<view class="pad-tb-20 display-sb align-items fontSize-26" v-if="type==2">
					<text>商家收件地址:</text><text>{{info?.shop_mail.mail_mobile}}</text>
				</view>
				<view class="pad-tb-20 display-sb align-items fontSize-26"
					v-if="type==2&&(info?.after.logistics_flow>1)">
					<text>寄回时间:</text><text>{{info?.after.user_return_time}}</text>
				</view>
				<view class="pad-tb-20 display-sb align-items fontSize-26"
					v-if="type==2&&(info?.after.logistics_flow>1)">
					<text>寄回单号:</text><text>{{info?.after.return_logistics_no}}</text> <text class="ml20"
						@click="copy(info?.after.return_logistics_no)">复制</text>
				</view>
				<!-- <view class="pad-tb-20 display-sb align-items fontSize-26 col-6" v-if="type==2&&(info?.after.return_type==3||info?.after.return_type==2)&&(info?.after.status==20||info?.after.status==30)">
			<text>平台确认收货时间:</text><text>{{info?.platform_confirm_time}}</text>
		</view> -->
				<view class="pad-tb-20 display-sb align-items fontSize-26"
					v-if="type==2&&(info?.after.logistics_flow==4)">
					<text>发货单号:</text><text>{{info?.after.logistics_no}}</text>
				</view>
				<!-- <view class="pad-tb-20 display-sb align-items fontSize-26 col-6" v-if="type==2&&info?.return_type==3&&info?.status==120">
			<text>确认收货时间:</text><text>{{info?.user_confirm_time}}</text>
		</view> -->
			</view>
		</view>
		<view class="poFi bottom-0 bgfff width-100">
			<view class="display-sb align-items pad-lr-30 bottom_view">
				<view class="fontSize-28">
					<view class="display align-items" v-if="info?.order.order_status==10">
						<tm-countdown ref="cu" :autoStart="true" format="MM分SS秒" @end="changetime"
							:time="info?.remaining_second*1000"></tm-countdown>后失效
					</view>
				</view>
				<view class="display align-items" v-if="order_type==1">
					<view class="pad-lr-18 pad-tb-12 fontSize-26 radius-30 borderccc" v-if="info?.order.order_status==1"
						@click="openshowWin(info?.order.id)">取消订单</view>
					<view class="pad-lr-32 pad-tb-12 fontSize-26 radius-30 col-f bg2DB295 ml20"
						v-if="info?.order.order_status==1" @click="wxpay(info?.order_code,info?.buy_type,'')">去付款</view>
					<view class="pad-lr-18 pad-tb-12 fontSize-26 radius-30 borderccc"
						v-if="info?.order.order_status==20" @click="goviewLogistics(info?.order.id)">查看物流</view>
					<view class="pad-lr-16 pad-tb-12 fontSize-26 radius-30 borderccc ml20"
						v-if="info?.order.order_status==15" @click="_applyAfter(info?.order.id,1)">申请退款</view>
					<view class="pad-lr-16 pad-tb-12 fontSize-26 radius-30 borderccc ml20"
						v-if="(info?.order.order_status==20||info?.order.order_status==30)&&info?.order.is_refund==1&&info?.goods.length==1"
						@click="_applyAfter(info?.order.id,3)">申请售后</view>

					<view class="pad-lr-16 pad-tb-12 fontSize-26 radius-30 col-f bg2DB295 ml20"
						v-if="info?.order.order_status==20" @click="_confirm_order(info?.id)">确认收货</view>
					<view class="pad-lr-32 pad-tb-12 fontSize-26 radius-30 col-f bg2DB295 ml20"
						v-if="info?.order.order_status==30&&info?.goods.length==1&&info?.goods[0].evaluate_status==0"
						@click="gowriteevaluate(info?.goods[0].id,info?.order.id)">评价</view>
					<!-- <view class="pad-lr-16 pad-tb-12 fontSize-26 radius-30 col-f bg2DB295 ml20" v-if="info?.status==110&&type==2" @click="_user_confirm_order(info?.id)">确认收货</view> -->
					<view class="pad-lr-16 pad-tb-12 fontSize-26 radius-30 col-f bg2DB295 ml20"
						v-if="(info?.after?.return_type==2||info?.after?.return_type==3)&&info?.after.logistics_flow==1&&type==2"
						@click="openshowcode">填写单号</view>
				</view>
				<view class="display align-items" v-if="order_type==2">
					<view class="pad-lr-32 pad-tb-12 fontSize-26 radius-30 col-f bg2DB295 ml20"
						v-if="info?.order.order_status==15" @click="openshopshowWincode(info?.order.id)">发货</view>
					<view class="pad-lr-18 pad-tb-12 fontSize-26 radius-30 borderccc"
						v-if="info?.order.order_status==20" @click="goviewLogistics(info?.order.id)">查看物流</view>
				</view>
			</view>
		</view>
		<!-- 取消订单提示框 -->
		<tm-overlay v-model:show="showWin" contentAnimation>
			<view @click.stop="">
				<view class="pad-lr-28 radius-32 bgfff pop_view pad-tb-50">
					<view class="text-align-center fontSize-32">是否确认取消订单？</view>
					<view class="mar-top-40 display-ce align-items">
						<view class="text-align-center fontSize-32 borderccc pad-lr-88 pad-tb-18 radius-40"
							@click="showWin = false">取消</view>
						<view class="text-align-center fontSize-32 bg2DB295 pad-lr-88 pad-tb-18 radius-40 col-f ml40"
							@click="_cancel_order">确认</view>
					</view>
				</view>
			</view>
		</tm-overlay>
		<!-- 填写寄回快递单号 -->
		<tm-overlay v-model:show="showWincode" contentAnimation>
			<view @click.stop="">
				<view class="pad-lr-28 radius-32 bgfff pop_view pad-tb-50">
					<view class="fontSize-32 mar-top-30">请填写物流公司名称</view>
					<view class="radius-16 bgf6 pad-lr-30 pad-tb-18 mar-top-10">
						<input type="text" placeholder="请填写" v-model="return_logistics_name" class="width-100" />
					</view>
					<view class="fontSize-32 mar-top-30">请填写寄回快递单号</view>
					<view class="radius-16 bgf6 pad-lr-30 pad-tb-18 mar-top-10">
						<input type="text" placeholder="请填写" v-model="express_code" class="width-100" />
					</view>
					<view class="mar-top-40 display-ce align-items">
						<view class="text-align-center fontSize-32 bg2DB295 pad-lr-88 pad-tb-18 radius-40 col-f ml40"
							@click="_user_add_express_code">提交</view>
					</view>
				</view>
			</view>
		</tm-overlay>
		<tm-overlay v-model:show="shopshowWincode" contentAnimation>
			<view @click.stop="">
				<view class="pad-lr-28 radius-32 bgfff pop_view pad-tb-50">
					<view class="fontSize-32 mar-top-30">请填写物流公司名称</view>
					<picker @change="bindPickerChange" :value="expressindex" range-key="name" :range="expressList">
						<view class="radius-16 bgf6 pad-lr-30 pad-tb-18 mar-top-10">
							<input type="text" placeholder="请填写" disabled v-model="express_name" class="width-100" />
						</view>
					</picker>
					<view class="fontSize-32 mar-top-30">请填写寄回快递单号</view>
					<view class="radius-16 bgf6 pad-lr-30 pad-tb-18 mar-top-10">
						<input type="text" placeholder="请填写" v-model="express_no" class="width-100" />
					</view>
					<view class="mar-top-40 display-ce align-items">
						<view class="text-align-center fontSize-32 bg2DB295 pad-lr-88 pad-tb-18 radius-40 col-f ml40"
							@click="_shopdeliver">发货</view>
					</view>
				</view>
			</view>
		</tm-overlay>
	</view>
</template>

<script lang="ts" setup>
	import { onLoad, onShow, onUnload } from '@dcloudio/uni-app';
	import { ref } from 'vue';
	import { orderInfo, payOrder, cancelOrder, afterInfo, confirmReceipt, afterSendBack, shoporderInfo,ajaxexpress,shopdeliver } from '@/utils/api'

	// 声明微信支付相关类型
	declare const WeixinJSBridge: any;
	declare const wx: any;
	onLoad((options) => {
		order_id.value = options.order_id
		if (options.type == 2) {
			type.value = options.type
			id.value = options.id
			_after_order_info()
		} else {
			order_type.value = options.order_type
			if (options.order_type == 1) {
				_order_detail()
			} else {
				_shoporderInfo()
			}
		}

	})
	onShow(() => {
		uni.$on('updatainfo', () => {
			_order_detail()
		})
		uni.$on('updatapingjia', () => {
			_order_detail()
		})
	})
	onUnload(() => {
		uni.$off('updatainfo')
		uni.$off('updatapingjia')
	})
	const type = ref(),//2-售后订单 id-售后订单存在
		id = ref(),
		order_type = ref();//1-会员订单 2-商户订单
	const order_id = ref()//订单id
	//订单详情数据
	const info = ref()
	const _order_detail = () => {
		orderInfo({ id: order_id.value }).then(res => {
			if (res.code == 1) {
				info.value = res.data
			}
		})
	}
	//商家订单信息
	const _shoporderInfo = () => {
		shoporderInfo({ id: order_id.value }).then(res => {
			if (res.code == 1) {
				info.value = res.data
			}
		})
	}
	//售后订单数据信息
	const _after_order_info = () => {
		afterInfo({ id: id.value }).then(res => {
			if (res.code == 1) {
				info.value = res.data
			}
		})
	}
	const showWin = ref(false)//取消订单提示框
	const showWincode = ref(false),//填写快递单号弹窗
		  shopshowWincode=ref(false)
	//倒计时
	const changetime = (e) => {
		clea_id.value = info.value.id
		_cancel_order()
	}
	//取消订单
	const openshowWin = (id : number | string) => {
		clea_id.value = id
		showWin.value = true
	}
	const clea_id = ref()
	const _cancel_order = () => {
		cancelOrder({ id: clea_id.value }).then(res => {
			uni.showToast({
				icon: 'none',
				title: res.msg
			})
			if (res.code == 1) {
				_order_detail()
				showWin.value = false
			}
		})
	}
	//确认收货
	const _confirm_order = (id : number | string) => {
		uni.showModal({
			title: '提示',
			content: '是否确认收货？',
			success: function (res) {
				if (res.confirm) {
					confirmReceipt({ id: id }).then(res => {
						uni.showToast({
							icon: 'none',
							title: res.msg
						})
						if (res.code == 1) {
							_order_detail()
						}
					})
				} else if (res.cancel) {
				}
			}
		})
	}

	const wxpay = (id : string) => {
		payOrder({
			id: id,
		}).then(res => {
			if (res.code == 1) {
			let data = JSON.parse(JSON.stringify(res.data))
			// 调用微信支付
			callWechatPayInOrderDetails(data)
			} else if (res.code == 555) {

			} else {
				uni.showToast({
					icon: 'none',
					title: res.msg
				})
			}
		})
	}
	//售后订单填写单号
	const express_code = ref()
	const return_logistics_name = ref()
	const openshowcode = () => {
		showWincode.value = true
	}
	const _user_add_express_code = () => {
		afterSendBack({ return_logistics_no: express_code.value, id: id.value, return_logistics_name: return_logistics_name.value }).then(res => {
			uni.showToast({
				icon: 'none',
				title: res.msg
			})
			if (res.code == 1) {
				showWincode.value = false
				_after_order_info()
			}
		})
	}
	//打电话
	const gotel = (tel : string | number) => {
		uni.makePhoneCall({
			phoneNumber: tel,
			success() {

			}
		})
	}
	//复制
	const copy = (e) => {
		uni.setClipboardData({
			data: e,
			success() {
				uni.showToast({
					title: '已复制',
					icon: 'success'
				})
			}
		})
	}
	const gomap = () => {
		uni.openLocation({
			latitude: Number(info.value?.merchant_lat),
			longitude: Number(info.value?.merchant_lng),
			address: info.value?.merchant_full_address,
			name: info.value?.merchant_name
		})
	}
	const expressList = ref(),//物流列表
		  expressindex=ref(0),//表示选择了 expressList 中的第几个
		  express_no=ref(),//单号
		  express_name=ref()
	const openshopshowWincode=(id:number|string)=>{
		ajaxexpress({id:id}).then(res=>{
			if(res.code==1){
				expressList.value = res.data
				shopshowWincode.value=true
			}
		})
	}
	const bindPickerChange=(e)=>{
		express_name.value = expressList.value[e.detail.value].name
		expressindex.value=e.detail.value
	}
	//发货
	const _shopdeliver=()=>{
		shopdeliver({
			id:info.value.order.id,
			express_id:expressList.value[expressindex.value].id,
			express_no:express_no.value
		}).then(res=>{
			if(res.code==1){
				_shoporderInfo()
				shopshowWincode.value=false
			}
			uni.showToast({
				icon: 'none',
				title: res.msg
			})
		})
	}
	const goservice = (e) => {
		uni.navigateTo({
			url: '/mypages/service/service?order_id=' + info.value.order.id + '&id=' + e.id
		})
	}
	const goseecode = (id : number) => {
		uni.navigateTo({
			url: '/indexpages/seecode/seecode?order_id=' + id
		})
	}
	//评价
	const gowriteevaluate = (id : number, order_id : number) => {
		uni.navigateTo({
			url: '/mypages/writeevaluate/writeevaluate?order_goods_id=' + id + '&order_id=' + order_id
		})
	}
	//商品详情
	const gogoodsdetails = (id : number) => {
		uni.navigateTo({
			url: '/indexpages/goodsDetail/goodsDetail?id=' + id
		})
	}
	//申请退款
	const _applyAfter = (id, type) => {
		uni.navigateTo({
			url: '/mypages/service/service?return_type=' + type + '&order_id=' + id
		})
	}
	const goviewLogistics = (id) => {
		uni.navigateTo({
			url: '/mypages/viewLogistics/viewLogistics?id=' + id
		})
	}

	// 调用微信支付
	const callWechatPayInOrderDetails = (payData: any) => {
		console.log('开始调用微信支付:', payData);
		console.log('WeixinJSBridge 存在:', typeof WeixinJSBridge !== 'undefined');
		console.log('wx 存在:', typeof wx !== 'undefined');
		
		// 等待微信环境加载完成
		const tryWechatPay = () => {
			if (typeof WeixinJSBridge !== 'undefined') {
				console.log('使用 WeixinJSBridge 调用微信支付');
				// 使用WeixinJSBridge调用微信支付
				WeixinJSBridge.invoke('getBrandWCPayRequest', {
					appId: payData.appId,
					timeStamp: payData.timeStamp,
					nonceStr: payData.nonceStr,
					package: payData.package,
					signType: payData.signType,
					paySign: payData.paySign
				}, (result: any) => {
					console.log('WeixinJSBridge 支付结果:', result);
					handlePayResultInOrderDetails(result);
				});
			} else if (typeof wx !== 'undefined') {
				console.log('使用 wx.chooseWXPay 调用微信支付');
				// 使用微信JS-SDK的支付接口
				wx.chooseWXPay({
					timestamp: payData.timeStamp,
					nonceStr: payData.nonceStr,
					package: payData.package,
					signType: payData.signType,
					paySign: payData.paySign,
					success: (result: any) => {
						console.log('wx.chooseWXPay 支付成功:', result);
						handlePayResultInOrderDetails({err_msg: 'get_brand_wcpay_request:ok'});
					},
					cancel: (result: any) => {
						console.log('wx.chooseWXPay 支付取消:', result);
						handlePayResultInOrderDetails({err_msg: 'get_brand_wcpay_request:cancel'});
					},
					fail: (result: any) => {
						console.log('wx.chooseWXPay 支付失败:', result);
						handlePayResultInOrderDetails({err_msg: 'get_brand_wcpay_request:fail'});
					}
				});
			} else {
				console.log('微信支付环境检查失败，等待加载...');
				// 如果微信环境还没加载完成，等待一下再试
				setTimeout(() => {
					if (typeof WeixinJSBridge !== 'undefined' || typeof wx !== 'undefined') {
						tryWechatPay();
					} else {
						uni.showToast({
							title: '请在微信中打开',
							icon: 'none'
						});
					}
				}, 1000);
			}
		};
		
		tryWechatPay();
	}

	// 处理支付结果
	const handlePayResultInOrderDetails = (result: any) => {
		if (result.err_msg === 'get_brand_wcpay_request:ok') {
			uni.showToast({
				icon: 'none',
				title: '支付成功！'
			})
			_order_detail()
		} else if (result.err_msg === 'get_brand_wcpay_request:cancel') {
			uni.showToast({
				icon: 'none',
				title: '已取消支付！'
			})
		} else {
			uni.showToast({
				icon: 'none',
				title: '支付失败！'
			})
		}
	}
</script>

<style lang="scss">
	@import 'orderdetails.scss';
</style>